package com.qzboot.basic.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.qzboot.basic.service.mapper.SysUserTokenMapper;
import com.qzboot.common.constant.SysConst;
import com.qzboot.facade.entity.SysUserToken;
import com.qzboot.facade.service.SysUserTokenService;
import com.qzboot.facade.support.CrudServiceImpl;
import org.apache.dubbo.config.annotation.Service;

import java.util.Date;

/**
 * @author zengzhihong
 */
@Service
public class SysUserTokenServiceImpl extends CrudServiceImpl<SysUserTokenMapper, SysUserToken> implements SysUserTokenService {

    @Override
    public SysUserToken getByToken(String token) {
        return baseMapper.selectOne(Wrappers.<SysUserToken>lambdaQuery().eq(SysUserToken::getToken, token));
    }

    @Override
    public SysUserToken createToken(Long userId, String username, String reqIp, String ipRegion) {
        //生成一个token
        String token = IdWorker.get32UUID();
        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + SysConst.SYS_TOKEN_EXPIRE_MS);

        //判断是否生成过token
        SysUserToken sysUserToken = baseMapper.selectOne(Wrappers.<SysUserToken>lambdaQuery().eq(SysUserToken::getUserId, userId));
        if (sysUserToken == null) {
            sysUserToken = new SysUserToken();
            sysUserToken.setUserId(userId);
            sysUserToken.setUsername(username);
            sysUserToken.setToken(token);
            sysUserToken.setExpireTime(expireTime);
            sysUserToken.setReqIp(reqIp);
            sysUserToken.setIpRegion(ipRegion);
            //保存token
            this.save(sysUserToken);
        } else {
            //token如果过期 重新生成token
            if (sysUserToken.getExpireTime().getTime() - 600000 < System.currentTimeMillis()) {
                sysUserToken.setToken(token);
            }
            sysUserToken.setUpdateTime(now);
            sysUserToken.setExpireTime(expireTime);
            sysUserToken.setReqIp(reqIp);
            sysUserToken.setIpRegion(ipRegion);
            //更新token
            baseMapper.updateById(sysUserToken);
        }
        return sysUserToken;
    }

    @Override
    public boolean removeByUserId(Long userId) {
        return SqlHelper.retBool(baseMapper.delete(Wrappers.<SysUserToken>lambdaQuery().eq(SysUserToken::getUserId, userId)));
    }
}
